﻿//
// Copyright (c) 2011 Canyala Innovation AB
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
// associated documentation files (the "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// copies of the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH 
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Canyala.Lagoon.Text;

namespace Canyala.Lagoon.Extensions
{
    public static class StringExtensions
    {
        static public IEnumerable<char> AsEnumerable(this string s)
        {
            return s.ToCharArray();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="self"></param>
        /// <param name="other"></param>
        /// <returns></returns>
        static public string CommonStartsWith(this string self, string other)
        {
            var builder = new StringBuilder();
            var otherEnum = other.AsEnumerable().GetEnumerator();
            var selfEnum = self.AsEnumerable().GetEnumerator();

            while (selfEnum.MoveNext() && otherEnum.MoveNext())
            {
                if (selfEnum.Current == otherEnum.Current)
                {
                    builder.Append(selfEnum.Current);
                    continue;
                }

                break;
            }

            return builder.ToString();
        }

        static public bool TryGetEnumPrefix(this string self, out string prefix)
        {
            prefix = string.Empty;
            var enumerator = self.AsEnumerable().GetEnumerator();
            var builder = new StringBuilder();

            while (enumerator.MoveNext())
                if (Char.IsLetter(enumerator.Current)) builder.Append(enumerator.Current);
                else if (Char.IsDigit(enumerator.Current))
                {
                    while (enumerator.MoveNext())
                        if (!Char.IsDigit(enumerator.Current)) return false;
                    prefix = builder.ToString();
                    return true;
                }
                else return false;

            return false;
        }

        public static SubString AsSubString(this string text)
            { return new SubString(text); }

        public static string AsCodeString(this string text)
        {
            var builder = new StringBuilder();

            builder
                .Append('"')
                .Append(text.EncodeEscape())
                .Append('"');

            return builder.ToString();
        }

        public static byte[] AsBytes(this string self, Encoding encoding)
            { return encoding.GetBytes(self); }

        public static byte[] AsUTF8(this string self)
            { return AsBytes(self, Encoding.UTF8); }

        public static string EncodeEscape(this string text)
        {
            var builder = new StringBuilder();

            foreach (var c in text)
                switch (c)
                {
                    case '\"':
                        builder.Append("\\\"");
                        break;
                    case '\\':
                        builder.Append("\\\\");
                        break;
                    case '\b':
                        builder.Append("\\b");
                        break;
                    case '\f':
                        builder.Append("\\f");
                        break;
                    case '\n':
                        builder.Append("\\n");
                        break;
                    case '\r':
                        builder.Append("\\r");
                        break;
                    case '\t':
                        builder.Append("\\t");
                        break;
                    default:
                        builder.Append(c);
                        break;
                }
            
            return builder.ToString();
        }

        public static string DecodeEscape(this string text)
        {
            var builder = new StringBuilder();
            var checkEscape = false;

            foreach (var c in text)
            {
                if (c == '\\')
                {
                    if (checkEscape)
                    {
                        builder.Append('\\');
                        checkEscape = false;
                        continue;
                    }

                    checkEscape = true;
                    continue;
                }

                if (checkEscape)
                {
                    checkEscape = false;

                    switch (c)
                    {
                        case '"':
                            builder.Append('"');
                            break;
                        case 'b':
                            builder.Append('\b');
                            break;
                        case 'f':
                            builder.Append('\f');
                            break;
                        case 'n':
                            builder.Append('\n');
                            break;
                        case 'r':
                            builder.Append('\r');
                            break;
                        case 't':
                            builder.Append('\t');
                            break;
                        default:
                            throw new FormatException("Unrecognizrd escape character \\{0}".Args(c));
                    }
                }
                else
                    builder.Append(c);
            }

            return builder.ToString();
        }

        public static string Args(this string format, params object[] arguments)
        { 
            return String.Format(format, arguments); 
        }

        public static bool HasValue(this string text)
        {
            return !string.IsNullOrEmpty(text);
        }

        /// <summary>
        /// Extension for strings that is a shortcut to create formatted strings with a 
        /// format provider.
        /// </summary>
        /// <param name="format">The string format expression.</param>
        /// <param name="formatProvider">A format provider to use when formatting text.</param>
        /// <param name="arguments">The arguments to format.</param>
        /// <returns>A formatted string with the arguments.</returns>
        /// <remarks>
        /// This extension is a short form for the <see cref="String.Format"/>
        /// method. It allows you to write, for example:
        /// <code>
        /// "{0}, {1}, {2}".Args(CultureInfo.CurrentCulture, 1, 2, 3)   // => "1, 2, 3"
        /// </code>
        /// Instead of:
        /// <code>
        /// String.Format(CultureInfo.CurrentCulture, "{0}, {1}, {2}", 1, 2, 3);
        /// </code>
        /// </remarks>
        public static string Args(this string format, IFormatProvider formatProvider, params object[] arguments)
        {
            return string.Format(formatProvider, format, arguments);
        }

        public static string Join(this IEnumerable<string> seqOfStrings, char separator)
        {
            var builder = new StringBuilder();

            foreach (var stringItem in seqOfStrings)
            {
                if (builder.Length > 0) builder.Append(separator);
                builder.Append(stringItem);
            }

            return builder.ToString();
        }

        public static string Join(this IEnumerable<string> seqOfStrings, string separator)
        {
            var builder = new StringBuilder();

            foreach (var stringItem in seqOfStrings)
            {
                if (builder.Length > 0) builder.Append(separator);
                builder.Append(stringItem);
            }

            return builder.ToString();
        }

        public static double AsDouble(this string text)
        {
            double value = 0.0;
            Double.TryParse(text, out value);
            return value;
        }

        public static long AsLong(this string text) 
        {
            long value = 0;
            long.TryParse(text, out value);
            return value;
        }

        public static int AsInt(this string text) 
        {
            int value = 0;
            int.TryParse(text, out value);
            return value;
        }

        public static bool Any(this string text, Predicate<char> predicate)
        {
            foreach (var c in text)
                if (predicate(c))
                    return true;

            return false;
        }

        public static T AsEnum<T>(this string text)
        {
            return (T)Enum.Parse(typeof(T), text, true);
        }
    }
}
